<?php

namespace Apps\Manage\Controllers;


use Apps\Common\Enum\BackendOpLog;
use Apps\Common\Models\BackendOperator;
use PhalconPlus\Operator\Models\Group as BackendOperatorGroup;
use Apps\Common\Models\BackendOperatorLog;
use Apps\Common\Models\BackendOperatorLogType;
use Phalcon\Mvc\View;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Models\SysOpenCity;
/**
 * 系统管理
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class SysController extends BaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->setMainNav('sys');
    }
	
    /**
     * 开通的城市
     * @return \Phalcon\Mvc\Model\Criteria
     */
    private function openCityList()
    {
    	return SysOpenCity::find("city_state = 1");
    }
    
    public function indexAction()
    {
        $this->response->redirect('sys/opList');
    }

    /**
     * 登录
     * @return ResponseResult
     */
    public function loginAction()
    {
        $req = $this->request;
        // 登录处理
        if($req->isPost())
        {
            $resp = new ResponseResult();
            $resp->callback = $req->getPost('callback', null, 'parent.setFormResult');
            $resp->callbackJavascriptTag = true;

            $account = $req->getPost('op_account');
            $password = $req->getPost('op_password');
            if(empty($account) || empty($password))
            {
                $errorMsg = '参数不能为空.';
                $this->operatorLog(0, BackendOpLog::PARAM_EXCEPTION, $errorMsg);
                $resp->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, $errorMsg);
                return $resp;
            }
            // 验证登录信息
            $userInfo = BackendOperator::query()
                ->where('operator_account=:account: AND operator_password=:pwd:')
                ->bind([
                    'account' => $account,
                    'pwd' => $this->operator->hashPassword($password),
                ])->execute()->getFirst();
            
            if(!$userInfo)
            {
                $errorMsg = '账户密码不一致或账户信息不存在!';
                $this->operatorLog(0, BackendOpLog::LOGIN_FAIL, $errorMsg . 'account: ' . $account . ', password: ' . $password);
                $resp->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, $errorMsg);
                return $resp;
            }
            if($userInfo->operator_state != 1)
            {
                $errorMsg = '账户已被停用，请联系管理员!';
                $this->operatorLog($userInfo->operator_id, BackendOpLog::LOGIN_FAIL, $errorMsg . 'account: ' . $account . ', password: ' . $password);
                $resp->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, $errorMsg);
                return $resp;
            }
            $userData = [
                'id' => $userInfo->operator_id,
                'name' => $userInfo->operator_show_name,
                'role' => $userInfo->operator_role,
                'group' => $userInfo->operator_group
            ];
            $this->operator->saveUserInfo($userData);
            $resp->sendResult('登录成功！');
            $this->cookies->send();
            $this->operatorLog($userInfo->operator_id, BackendOpLog::LOGIN_SUCCESS, '登录成功.');
            return $resp;
        }
    }

    /**
     * 退出登录
     */
    public function logoutAction()
    {
        $this->operator->logout();
        $this->response->redirect($this->di->get('moduleConfig')->operator->login->url);
        $this->view->disable();
        $this->operatorLog($this->operator->id, BackendOpLog::LOGOUT, '退出登录');
    }

    public function updatePwdAction()
    {
        $this->setMainNav('self');
        $req = $this->request;
        if(!$req->isPost()){
            return;
        }

        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;

        $oldPwd = $req->getPost('oldPassword');
        $newPwd = $req->getPost('newPassword');

        if(!$oldPwd || !$newPwd) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }
        $userId = $this->operator->id;
        $info = BackendOperator::findFirst('operator_id = ' . $userId);
        if(!$info) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }
        if($info->operator_password != $this->operator->hashPassword($oldPwd)) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '旧密码错误！');
            return $response;
        }
        $info->update([
            'operator_password' => $this->operator->hashPassword($newPwd)
        ]);
        $response->sendResult('ok');
        return $response;
    }

    /**
     * 操作日志
     */
    public function opLogAction()
    {
        $this->setLeftNav('opLog');
        $req = $this->request;
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $filterOp = intval($req->getQuery('filterOp', null,-10000));
        $filterType = intval($req->getQuery('filterType', null, -10000));
        $where = [];
        $bindParams = [];
        if($filterOp > -10000)
        {
            $where[] = 'Apps\Common\Models\BackendOperatorLog.operator_id = :opId:';
            $bindParams['opId'] = $filterOp == -10000 ? 0 : $filterOp;
        }
        if($filterType > -10000)
        {
            $where[] = 'log_type = :opType:';
            $bindParams['opType'] = $filterType;
        }
        $whereStr = implode(' AND ', $where);

        // 总数
        $total = BackendOperatorLog::count([
            'conditions' => $whereStr,
            'bind' => $bindParams,
        ]);

        // 操作员列表
        $opList = BackendOperator::find();
        $this->view->setVar('opList', $opList);

        // 操作类型
        $this->view->setVar('opLogTypes', BackendOperatorLogType::find());

        $data = BackendOperatorLog::query()
            ->columns([
                'Apps\Common\Models\BackendOperatorLog.log_id',
                'op.operator_id',
                'op.operator_show_name',
                'logType.type_title log_type',
                'Apps\Common\Models\BackendOperatorLog.log_client_info',
                'Apps\Common\Models\BackendOperatorLog.log_addtime'
            ])
            ->where($whereStr)
            ->bind($bindParams)
            ->leftJoin('Apps\Common\Models\BackendOperator', 'op.operator_id = Apps\Common\Models\BackendOperatorLog.operator_id', 'op')
            ->leftJoin('Apps\Common\Models\BackendOperatorLogType', 'logType.type_id = Apps\Common\Models\BackendOperatorLog.log_type', 'logType')
            ->limit($limit, ($page - 1) * $limit)
            ->orderBy('Apps\Common\Models\BackendOperatorLog.log_id DESC')
            ->execute();

        $this->view->setVar('total', $total);
        $this->view->setVar('page', $page);
        $this->view->setVar('limit', $limit);

        $this->view->setVar('filterOp', $filterOp);
        $this->view->setVar('filterType', $filterType);
        $this->view->setVar('data', $data);
    }

    /**
     * 操作员列表
     */
    public function opListAction()
    {
        $this->setLeftNav('opList');
        $this->view->setVar('data', BackendOperator::query()
            ->columns([
                'operator_id',
                'operator_show_name',
                'operator_remark',
                'operator_state',
                'operator_addtime',
                'g.group_name group_name'
            ])
            ->leftJoin('PhalconPlus\Operator\Models\Group', 'group_id = operator_group', 'g')
            ->where('operator_id > 0')
            ->execute());
    }

    /**
     * 操作员账号是否存在
     */
    public function opExistAction()
    {
        $this->view->disable();
        $account = $this->request->getQuery('operator_account');
        if(empty($account))
        {
            echo '{"error": "不能为空!"}';
            return;
        }
        if(BackendOperator::count([
                'conditions' => 'operator_account = :account:',
                'bind' => ['account' => $account],
            ]) > 0)
        {
            echo '{"error":"此账户名称已经存在!"}';
        } else
        {
            echo '{"ok":""}';
        }
    }

    /**
     * 添加操作员
     */
    public function opAddAction()
    {
        $this->setLeftNav('opAdd');
        $req = $this->request;
        if(!$req->isPost()){
        	$this->view->setvar('opencity',$this->openCityList());
            $this->view->setVar('opGroup', BackendOperatorGroup::find());
            return;
        }

        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;

        $opAccount = $req->getPost('operator_account');
        $opShowName = $req->getPost('operator_show_name');
        $opPassword = $req->getPost('operator_password');
        $opRole = 0;
        $opGroup = intval($req->getPost('operator_group'));
        $opRemark = $req->getPost('operator_remark', null, '');

        if(!$opAccount || !$opShowName || !$opPassword || $opGroup < 0) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }

        if(BackendOperator::count([
                'conditions' => 'operator_account = :account:',
                'bind' => ['account' => $opAccount],
            ]) > 0)
        {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '此账户名称已经存在！');
            return $response;
        }

        $op = new BackendOperator();
        $op->operator_account = $opAccount;
        $op->operator_show_name = $opShowName;
        $op->operator_password = $this->operator->hashPassword($opPassword);
        $op->operator_role = $opRole;
        $op->operator_group = $opGroup;
        $op->operator_remark = $opRemark;

        if($op->save()){
            $response->sendResult($op->operator_id);
            $this->operatorLog($this->operator->id, BackendOpLog::APPEND_OPERATOR_SUCCESS, $opAccount . ',' . $opShowName);
        }else{
            $this->databaseErrorLog($op);
            $error = '保存数据异常！';
            $response->sendError(ResponseResultStatus::DATABASE_ERROR, $error);
            $this->operatorLog($this->operator->id, BackendOpLog::APPEND_OPERATOR_FAILED, $error);
        }
        return $response;
    }


    /**
     * 设置操作员状态
     * @return $this|ResponseResult
     */
    public function opSetStateAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $state = intval($req->getPost('state', null, -10000));
            if(!in_array($state, [-1, 0, 1])) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = BackendOperator::findFirst('operator_id = ' . $id);
            if($info) {
                $info->update(['operator_state' => $state]);
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 修改密码
     * @return $this|ResponseResult
     */
    public function opUpdatePwdAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $pwd = $req->getPost('pwd');
            if(!$pwd) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = BackendOperator::findFirst('operator_id = ' . $id);
            if($info) {
                $info->update(['operator_password' => $this->operator->hashPassword($pwd)]);
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 修改操作员基础信息
     */
    public function opUpdateBaseAction()
    {
        $req = $this->request;
        if(!$req->isPost()) {
            $id = intval($req->getQuery('id', null, 0));
            $this->view->setVar('id', $id);
            $this->view->setVar('opInfo', BackendOperator::findFirst('operator_id = ' . $id));
            $this->view->setVar('opGroup', BackendOperatorGroup::find());
            return;
        }

        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;

        $opId = intval($req->getPost('operator_id', null, 0));
        $opAccount = $req->getPost('operator_account');
        $opShowName = $req->getPost('operator_show_name');
        $opGroup = intval($req->getPost('operator_group'));
        $opRemark = $req->getPost('operator_remark', null, '');

        if($opId <= 0 || !$opAccount || !$opShowName || $opGroup < 0) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }

        $accountExist = BackendOperator::query()
            ->where('operator_account = :account:', ['account' => $opAccount])
            ->execute()
            ->getFirst();
        if(!!$accountExist && $accountExist->operator_id != $opId) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '此账户名称已经存在！');
            return $response;
        }
        $info = BackendOperator::findFirst('operator_id = ' . $opId);
        $data = [];
        if($info->operator_account != $opAccount) {
            $data['operator_account'] = $opAccount;
        }
        if($info->operator_show_name != $opShowName) {
            $data['operator_show_name'] = $opShowName;
        }
        if($info->operator_group != $opGroup) {
            $data['operator_group'] = $opGroup;
        }
        if($info->operator_remark != $opRemark) {
            $data['operator_remark'] = $opRemark;
        }
        $info->update($data);
        $response->sendResult('ok');
        return $response;
    }
}